﻿package controllers  {
	
	import flash.events.ErrorEvent;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.text.TextFieldAutoSize;
	import models.MainModel;
	import models.types.SectionType;
	import models.types.SubsectionType;
	
	public class Controller {
		
		private var model:MainModel;

		public function Controller() {
			model = new MainModel();
		}
		
		public function init(url:String):void
		{
			var xml_loader:URLLoader = new URLLoader();
			
			xml_loader.addEventListener(Event.COMPLETE, parse, false, 0, true); 
			xml_loader.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);            
			xml_loader.load(new URLRequest(url));
		}
		
		private function errorHandler(e:IOErrorEvent):void
		{
			Main.instance.error_txt.autoSize = TextFieldAutoSize.CENTER;
			Main.instance.error_txt.text = "Неправильное имя либо путь к XML файлу";
			//Main.instance.error_txt.appendText(Main.instance.xml_path);
		}
		
		private function parse(e:Event):void
		{
			var main_xml:XML = XML(e.target.data);
			var sections_list:XMLList = main_xml.item;

			var section_id:int = 0;
			var sections:Array = [];
			
			for each (var section_item:XML in sections_list) 
			{
				var subsection_id:int = 0;
				var subsections:Array = [];
				
				var section:SectionType = new SectionType();
				
				section.title = section_item.@title;
				section.url = section_item.url;
				
				var subsections_list:XMLList = section_item.subitem;
				
				for each (var subsection_item:XML in subsections_list) 
				{
					var subsection:SubsectionType = new SubsectionType();
					
					subsection.id = subsection_id;
					subsection.caption = subsection_item.caption;
					subsection.url = subsection_item.url;
					
					subsections.push(subsection);
					
					subsection_id ++;
				}
				
				section.id = section_id;
				section.subsections = subsections;
				section.total_subsections = subsection_id;
				
				section_id ++ ;
				sections.push(section);
			}
			
			model.sections = sections;
			model.total_sections = section_id;
		}

	}
	
}
